/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.stakeholder;

import exception.ExistException;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.event.ActionEvent;
import javax.faces.bean.ManagedBean;
import session.stateless.StakeholderSessionBeanStateless;
import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import managedbean.PageRedirectorBean;
import session.stateless.SystemMessagesBean;
import util.entityhelper.StakeholderAccountState;
import util.localization.WebLocalization;

/**
 *
 * @author jamie
 */
@ManagedBean
//@SessionScoped
@RequestScoped
public class StakeholderLoginManagedBean implements Serializable {

    @EJB
    private StakeholderSessionBeanStateless stakeholderAccountMgt;
    // EXCEPTION
    @EJB
    private SystemMessagesBean systemMessages;
    private WebLocalization localization;
    //  user preferred locale
    private String preferredLocale;
    private String username;
    private String password;
    private boolean loggedIn = false;
    private String nextPage;
    //for remembering me
    private boolean remember;
    private String r;
    //for cookie storage
    private final int cookieTime = 10;
    private StakeholderAccountState stakeholderState;
    private PageRedirectorBean redirect = new PageRedirectorBean();

    public StakeholderLoginManagedBean() {
        checkCookie();
        /* LOCALIZATION */
        localization = new WebLocalization();
        preferredLocale = localization.getPreferredLocaleFromSession();
        /* END LOCALIZATION */

        /* pre-load values from session and database */
        // check if already logged in...redirect to tourist view page (home)
        if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().containsKey("stakeholderId")) {
            // redirect back to login
            nextPage = FacesContext.getCurrentInstance().getExternalContext().encodeActionURL(FacesContext.getCurrentInstance().getApplication().getViewHandler().getActionURL(FacesContext.getCurrentInstance(), "/stakeholder/ViewStakeholderAccount.xhtml"));
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect(getNextPage());
            } catch (IOException ioe) {
                ioe.printStackTrace();

            }
        }
        /* END load values from session and database */

    }

    public void doLogin(ActionEvent event) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        try {
            System.out.println("trying to retrieve user account details....");
            stakeholderState = getStakeholderAccountMgt().getStakeholderByUsername(username);

            System.out.println("retrieved detail..... verifying...");

            if (stakeholderState == null) {
                // before login
                System.out.println("invalid username entered: " + username);
                String statusMessage = systemMessages.getSystemMessage("STAKEHOLDERACCOUNT_ACCT_DOES_NOT_EXIST", preferredLocale);
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, statusMessage, "statusMessages"));

            } else {
                if (remember == false) {
                    r = "false";
                } else {
                    r = "true";
                }

                Cookie usernameCookie = new Cookie("usernameCookie", username);
                Cookie passwordCookie = new Cookie("passwordCookie", password);
                Cookie rememberCookie = new Cookie("rememberCookie", r);
                usernameCookie.setMaxAge(cookieTime);
                passwordCookie.setMaxAge(cookieTime);
                rememberCookie.setMaxAge(cookieTime);

                // after login
                setPassword(encrypt(password));
                if (stakeholderState.getPassword().equals(password)) {
                    //after getting username; check user is it verified.
                    if (stakeholderState.isVerified()) {
                        System.out.println("activation code: " + stakeholderState.isVerified());

                        if (r.equals("true")) {
                            System.out.println("what is remember me? " + remember);

                            ((HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse()).addCookie(usernameCookie);
                            ((HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse()).addCookie(passwordCookie);
                            ((HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse()).addCookie(rememberCookie);
                        }
                        //FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("savedLocale", preferredLocale);

                        //create a new session
                        // check if session has anything..default values if nothing
                        if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().isEmpty()) {
                            // create a session if no session created. get whatever user uses currently
                            FacesContext.getCurrentInstance().getExternalContext().getSession(true);
                        } else {
                            if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().containsKey("serverPort")) {
                                // if there is a previous session to pass the serverPort, retrieve the server port and destroy then create a new session and place the server port inside.
                                int serverPort = (Integer) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("serverPort");
                                String selectedLocale = "";
                                if (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().containsKey("selectedLocale")) {
                                    selectedLocale = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("selectedLocale").toString();
                                }
                                // clear previous session
                                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().clear();
                                // create a new session and add the server port.
                                FacesContext.getCurrentInstance().getExternalContext().getSession(true);
                                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("serverPort", serverPort);
                                FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("selectedLocale", selectedLocale);
                            }
                        }

                        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("stakeholderId", stakeholderState.getId());
                        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("stakeholderUsername", stakeholderState.getUsername());

                        redirect.goStakeholderAccountPage();

                    }//end of stakeholder is verified;
                    else {
                        String statusMessage = systemMessages.getSystemMessage("STAKEHOLDER_NOT_YET_ACTIVATED", preferredLocale);

                        System.out.println("activation code: " + stakeholderState.isVerified());
                        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, "statusMessages"));
                    }
                } else {
                    String statusMessage = systemMessages.getSystemMessage("STAKEHOLDER_LOGIN_INCORRECT", preferredLocale);
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, "statusMessages"));
                }
            }

        } catch (ExistException ex) {
            // EXCEPTION
            String statusMessage = systemMessages.getSystemMessage("STAKEHOLDER_LOGIN_FAIL", preferredLocale);
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, statusMessage, statusMessage));
        }
    }
    
    //encrypting the password
    public String encrypt(String inputString) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        String outputString = util.service.PasswordService.getInstance().encrypt(inputString);
        return outputString;
    }

    private void checkCookie() {
        String cookieName = null;
        Cookie cookie[] = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getCookies();
        if (cookie != null && cookie.length > 0) {
            for (int i = 0; i < cookie.length; i++) {
                cookieName = cookie[i].getName();
                if (cookieName.equals("usernameCookie")) {
                    username = cookie[i].getValue();
                    System.out.println("YAY");
                } else if (cookieName.equals("passwordCookie")) {
                    setPassword(cookie[i].getValue());
                    System.out.println("YAY2");
                } else if (cookieName.equals("rememberCookie")) {
                    r = cookie[i].getValue();
                    if (r.equals("false")) {
                        setRemember(false);
                    } else if (r.equals("true")) {
                        setRemember(true);
                    }
                }
            }
        } else {
            System.out.println("Cannot find any cookie");
        }
    }

    /**
     * @return the username
     */
    public String getUsername() {
        if (remember == false) {
            username = "";
        }
        return username;
    }

    /**
     * @return the password
     */
    public String getPassword() {
        if (remember == false) {
            password = "";
        }
        return password;
    }

    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }

    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * @return the loggedIn
     */
    public boolean isLoggedIn() {
        return loggedIn;
    }

    /**
     * @param loggedIn the loggedIn to set
     */
    public void setLoggedIn(boolean success) {
        this.loggedIn = success;
    }

    /**
     * @return the remember
     */
    public boolean isRemember() {
        return remember;
    }

    /**
     * @param remember the remember to set
     */
    public void setRemember(boolean remember) {
        this.remember = remember;
    }

    /**
     * @return the r
     */
    public String getR() {
        return r;
    }

    /**
     * @param r the r to set
     */
    public void setR(String r) {
        this.r = r;
    }

    /**
     * @return the nextPage
     */
    public String getNextPage() {
        return "StakeholderRegister?faces-redirect=true";
    }

    /**
     * @param nextPage the nextPage to set
     */
    public void setNextPage(String nextPage) {
        this.nextPage = nextPage;
    }

    /**
     * @return the stakeholderAccountMgt
     */
    public StakeholderSessionBeanStateless getStakeholderAccountMgt() {
        return stakeholderAccountMgt;
    }

    /**
     * @param stakeholderAccountMgt the stakeholderAccountMgt to set
     */
    public void setStakeholderAccountMgt(StakeholderSessionBeanStateless stakeholderAccountMgt) {
        this.stakeholderAccountMgt = stakeholderAccountMgt;
    }

    /**
     * @return the systemMessages
     */
    public SystemMessagesBean getSystemMessages() {
        return systemMessages;
    }

    /**
     * @param systemMessages the systemMessages to set
     */
    public void setSystemMessages(SystemMessagesBean systemMessages) {
        this.systemMessages = systemMessages;
    }

    /**
     * @return the localization
     */
    public WebLocalization getLocalization() {
        return localization;
    }

    /**
     * @param localization the localization to set
     */
    public void setLocalization(WebLocalization localization) {
        this.localization = localization;
    }

    /**
     * @return the preferredLocale
     */
    public String getPreferredLocale() {
        return preferredLocale;
    }

    /**
     * @param preferredLocale the preferredLocale to set
     */
    public void setPreferredLocale(String preferredLocale) {
        this.preferredLocale = preferredLocale;
    }

    public void logout(ActionEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("stakeholderAccountState", null);
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("StakeholderLogin.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(StakeholderLoginManagedBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @return the redirect
     */
    public PageRedirectorBean getRedirect() {
        return redirect;
    }

    /**
     * @param redirect the redirect to set
     */
    public void setRedirect(PageRedirectorBean redirect) {
        this.redirect = redirect;
    }
}
